package com.hqd.ch03.v22.aop.support;

import com.hqd.ch03.v22.aop.ClassFilter;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.tools.PointcutParser;
import org.aspectj.weaver.tools.TypePatternMatcher;
import org.junit.Assert;

public class TypePatternClassFilter implements ClassFilter {
    private String typePattern = "";
    private TypePatternMatcher aspectJTypePatternMatcher;

    public TypePatternClassFilter() {
    }

    public TypePatternClassFilter(String typePattern) {
        setTypePattern(typePattern);
    }

    @Override
    public boolean matches(Class<?> clazz) {
        Assert.assertNotNull(this.aspectJTypePatternMatcher);
        return this.aspectJTypePatternMatcher.matches(clazz);
    }

    public String getTypePattern() {
        return typePattern;
    }

    public void setTypePattern(String typePattern) {
        Assert.assertNotNull("匹配类型不能为空", typePattern);
        this.typePattern = typePattern;
        this.aspectJTypePatternMatcher = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution().
                parseTypePattern(replaceBooleanOperators(typePattern));
    }

    private String replaceBooleanOperators(String pcExpr) {
        String result = StringUtils.replace(pcExpr, " and ", " && ");
        result = StringUtils.replace(result, " or ", " || ");
        return StringUtils.replace(result, " not ", " ! ");
    }
}
